//
//  NEBaseTeamHistoryFileMessageController.swift
//  NETeamUIKit
//
//  Created by Laura on 2024/7/31.
//


import NECommonKit
import NIMSDK
import UIKit
import NEChatUIKit

private let cellId = "cellId"
private let headId = "headId"

@objcMembers
open class NEBaseTeamHistoryFileMessageController: NEBaseViewController, UITableViewDelegate, UITableViewDataSource, UIDocumentInteractionControllerDelegate {
    public let viewModel = TeamHistoryMessageViewModel()
    
    /// 群id
    public var teamId: String?
    var tag = "TeamHistoryFileMessageController"
    
    let interactionController = UIDocumentInteractionController()
    
    /// 历史消息列表
    public lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(
            NEBaseHistoryMessageCell.self,
            forCellReuseIdentifier: "\(NSStringFromClass(NEBaseTeamSearchFileCell.self))"
        )
        tableView.rowHeight = 65
        tableView.backgroundColor = .white
        tableView.sectionHeaderHeight = 30
        tableView.sectionFooterHeight = 0
        tableView.keyboardDismissMode = .onDrag
        
        if #available(iOS 11.0, *) {
            tableView.estimatedRowHeight = 0
            tableView.estimatedSectionHeaderHeight = 0
            tableView.estimatedSectionFooterHeight = 0
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0.0
        }
        return tableView
    }()
    
    /// 空占位图
    public lazy var emptyView: NEEmptyDataView = {
        let view = NEEmptyDataView(
            imageName: "emptyView",
            content: localizable("no_search_results"),
            frame: CGRect.zero
        )
        view.translatesAutoresizingMaskIntoConstraints = false
        view.isUserInteractionEnabled = false
        view.isHidden = true
        return view
        
    }()
    
    public init(teamId: String?) {
        super.init(nibName: nil, bundle: nil)
        self.teamId = teamId
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        weak var weakSelf = self
        
        viewModel.getTeamInfo(teamId) { team, error in
            if team?.isValidTeam == false || team == nil {
                weakSelf?.view.makeToast(localizable("team_not_exist"))
            }
        }
        setupSubviews()
        initialConfig()
    }
    
    open func setupSubviews() {
        
        view.addSubview(tableView)
        view.addSubview(emptyView)
        
        emptyView.isHidden = true
        
        NSLayoutConstraint.activate([
            emptyView.rightAnchor.constraint(equalTo: tableView.rightAnchor),
            emptyView.leftAnchor.constraint(equalTo: tableView.leftAnchor),
            emptyView.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
            emptyView.topAnchor.constraint(equalTo: tableView.topAnchor),
        ])
    }
    
    open func initialConfig() {
        title = localizable("team_file")
        
        toSearchHistory()
    }
    
    /// 搜索历史消息
    func toSearchHistory() {
        viewModel.searchResultInfos?.removeAll()
        tableView.reloadData()
        
        guard let teamId = teamId else {
            return
        }
        weak var weakSelf = self
        weakSelf?.viewModel.searchHistoryFileMessages(teamId) { error, messages in
            NEALog.infoLog(
                ModuleName + " " + self.tag,
                desc: "CALLBACK searchHistoryFileMessages " + (error?.localizedDescription ?? "no error")
            )
            if error == nil {
                if let msg = messages, msg.count > 0 {
                    weakSelf?.emptyView.isHidden = true
                } else {
                    weakSelf?.emptyView.isHidden = false
                }
                weakSelf?.tableView.reloadData()
            } else {
                NEALog.errorLog(
                    ModuleName + " " + (weakSelf?.tag ?? "TeamHistoryMessageController"),
                    desc: "searchMessages failed, error = \(error!)"
                )
            }
        }
    }
    
    // MARK: UITableViewDelegate, UITableViewDataSource
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewModel.searchFileResultInfos.count
    }
    
    open func tableView(_ tableView: UITableView,
                        cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        UITableViewCell()
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 98
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let message = viewModel.searchFileResultInfos[indexPath.row]
        toFileDetail(message)
    }
    
    /// 跳转文件查看器
    /// - Parameter model: 标记对象
    public func toFileDetail(_ message: HistoryMessageModel) {
        if let object = message.imMessage?.attachment as? V2NIMMessageFileAttachment {
            
            let fileModel = MessageFileModel(message: message.imMessage)
            
            // 判断状态，如果是下载中不能进行预览
            if fileModel.state == .Downalod {
                NEALog.infoLog(ModuleName + " " + className(), desc: #function + "downLoad state, click ingore")
                return
            }
            
            let path = object.path ?? ChatMessageHelper.createFilePath(message.imMessage)
            if !FileManager.default.fileExists(atPath: path) {
                // 本地文件不存在开始下载
                if let urlString = object.url {
                    downloadFile(fileModel, urlString, path)
                }
            } else {
                // 有则直接加载
                let url = URL(fileURLWithPath: path)
                interactionController.url = url
                interactionController.delegate = self
                
                if interactionController.presentPreview(animated: true) {}
                else {
                    interactionController.presentOptionsMenu(from: view.bounds, in: view, animated: true)
                }
            }
        }
    }
    
    /// 下载文件
    ///  - Parameter fileModel: 文件对象
    ///  - Parameter urlString: 下载地址
    ///  - Parameter path: 保存路径
    open func downloadFile(_ fileModel: MessageFileModel, _ urlString: String, _ path: String) {
        fileModel.state = .Downalod
        
        // 开始下载
        viewModel.downLoad(urlString, path) { [weak self] progress in
            
            NEALog.infoLog(ModuleName + " " + (self?.className() ?? ""), desc: #function + "downLoad file progress: \(progress)")
            
            // 根据进度设置状态
            fileModel.progress = progress
            
            if progress >= 100 {
                fileModel.state = .Success
            }
            // 更新ui进度
            fileModel.cell?.uploadProgress(progress)
        } _: { [weak self] localPath, error in
            if let err = error {
                switch err.code {
                case protocolSendFailed:
                    self?.showToast(commonLocalizable("network_error"))
                default:
                    print(err.localizedDescription)
                }
            } else if localPath != nil {
                fileModel.state = .Success
            }
        }
    }
    
    // MARK: UIDocumentInteractionControllerDelegate
    open func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        self
    }
    
    open func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        controller.dismiss(animated: true)
    }
}
